#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <errno.h>
#include <mqueue.h>

#define QUEUE_NAME  "/test_queue"
#define MAX_SIZE    4096
#define MSG_STOP    "exit"

int mq_send_process()
{
    int ret = 0;
    mqd_t mq = 0;
    char buffer[MAX_SIZE];

    mq = mq_open(QUEUE_NAME, O_WRONLY);
    if (mq < 0) {
        fprintf(stderr, "mq_open failed: %s\n", strerror(errno) );
        ret = -1;
        goto out;
    }

    do {
        printf("> ");
        fflush(stdout);

        memset(buffer, 0, MAX_SIZE);
        fgets(buffer, MAX_SIZE, stdin);

        int byte_sent = 0;
        byte_sent = mq_send(mq, buffer, MAX_SIZE, 0);
        if (byte_sent < 0) {
            fprintf(stderr, "mq_send failed: %s\n", strerror(errno) );
            ret = -1;
            goto out;            
        }

    } while (strncmp(buffer, MSG_STOP, strlen(MSG_STOP)));


out:
    if (mq) {
        if (mq_close(mq)) {
            fprintf(stderr, "mq_close failed: %s\n", strerror(errno) );
        }
    }
    return ret;
}

int main()
{
    mq_send_process();
    return 0;
}